package com.ccplay.dataservice.service.impl;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.oxygen.service.impl.SuperServiceImpl;
import com.ccplay.dataservice.service.CdnService;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;

@Service
public class CdnServiceImpl extends SuperServiceImpl implements CdnService {

	private static final Logger loger = Logger.getLogger(CdnServiceImpl.class);

	@Value("${cdn.accessKey}")
	private String cdnAccessKey;

	@Value("${cdn.secretKey}")
	private String cdnSecretKey;

	@Value("${cdn.defaultBucketName}")
	private String cdnDefaultBucketName;

	@Async
	@Override
	public PutRet putFileToCdn(String key, String fileFullPath) {
		try {
			Mac mac = new Mac(cdnAccessKey, cdnSecretKey);
			PutPolicy putPolicy = new PutPolicy(cdnDefaultBucketName);
			String uptoken = putPolicy.token(mac);
			PutExtra extra = new PutExtra();
			PutRet putRet = IoApi.putFile(uptoken, key, fileFullPath, extra);
			if (putRet != null) {
				loger.info("putFileToCdn.putRet=" + putRet.getResponse());
				return putRet;
			}
		} catch (AuthException e) {
			loger.error(e);
		} catch (JSONException e) {
			loger.error(e);
		} catch (Exception e) {
			loger.error(e);
		}
		return null;
	}

	public String getToken(String bucketName) {
		try {
			Mac mac = new Mac(cdnAccessKey, cdnSecretKey);
			if (StringUtils.isEmpty(bucketName)) {
				bucketName = cdnDefaultBucketName;
			}
			PutPolicy putPolicy = new PutPolicy(cdnDefaultBucketName);
			String uptoken = putPolicy.token(mac);
			return uptoken;
		} catch (AuthException e) {
			loger.error(e);
		} catch (JSONException e) {
			loger.error(e);
		} catch (Exception e) {
			loger.error(e);
		}
		return null;
	}
}
